package edu.biwu.main.java.edu.biwu.json;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONWriter;
import edu.biwu.main.java.edu.biwu.Student;
import org.junit.Test;


/*
* 这个问题以前遇到过，其实就是重新下载全部的包就行，但实在是太烦了，要不把day01模块删了吧
* 这个结构不对
*
* 哪一个是你的项目？
*
* 可以这样，那么原来main中的文件就当做某一个包下的文件来储存了
* 这其实是重复的吧？
* 额，太久远了，我实在忘了当初是怎么回事了，反正就 cn.hutool.json.JSONUtil;
* 这个包出了好多次错误，我想了想要是再犯，就全删了，
* 理解，lib手动导包 回去找这个包在的路径
* */

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JSONTest02 {
    @Test
    public void testObjectToJSON(){
        Student stu01 = new Student(20120913, "张三", "男", 12);
        System.out.println(JSONUtil.toJsonStr(stu01));
    }

    @Test
    public void testJSONToObject(){
        String jsonStr="{\"age\":12,\"gender\":\"男\",\"name\":\"张三\",\"sno\":20120913}";
        Student stu01 = JSON.parseObject(jsonStr, Student.class);
        System.out.println(stu01);
    }


    @Test
    public void testListToJSON(){
        List<Student> students = Arrays.asList(
                new Student(20120913, "张三", "男", 12),
                new Student(20120923, "李四", "男", 13)
        );
        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }

    @Test
    public void testJSONToList(){
        String jsonStr="[{\"age\":12,\"gender\":\"男\",\"name\":\"张三\",\"sno\":20120913},{\"age\":13,\"gender\":\"男\",\"name\":\"李四\",\"sno\":20120923}]";
        JSONArray.parseArray(jsonStr, Student.class).forEach(System.out::println);

    }


    @Test
    public void testMapToJSON(){
        List<Student> students = Arrays.asList(
                new Student(20120913, "张三", "男", 12),
                new Student(20120923, "李四", "男", 13)
        );

        Map<String, Student> collect = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + " ", stu -> stu));
        System.out.println(JSON.toJSONString(collect));
        System.out.println(JSON.toJSONString(collect, JSONWriter.Feature.PrettyFormat));
    }
}
